package listbyorder.access001_100.test19;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/28 12:50
 */
public class Solution2 {

    // 方法二：首先遍历出当前链表的长度
    // 删除倒数第n个节点就是删除正数（len - n + 1）个节点
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            len++;
            temp = temp.next;
        }
        // 删除第（len - n + 1）个节点
        int cur = len - n + 1;
        temp = head;
        if (cur == 1) return head.next;
        while (cur > 2) {
            temp = temp.next;
            cur--;
        }
        temp.next = temp.next.next;
        return head;
    }
}
